import axios from "axios";
import Cookies from 'js-cookie';
import {clearLoginInfo} from "@/utils/index.ts";
import router from "@/router";

const http = axios.create({
    timeout: 1000 * 30,
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    },
    allowAbsoluteUrls: false,
    baseURL: "http://localhost:8080" // todo: 生产环境和开发环境url配置
});

/**
 * 请求拦截器
 */
http.interceptors.request.use(config => {
    config.headers['token'] = Cookies.get('token');
    return config;
});

/**
 * 响应拦截器
 */
http.interceptors.response.use(res => {
    if (res.data && res.data.code === 401) {
        clearLoginInfo();
        router.push({name: 'login'})
    }
    return res;
}, error => Promise.reject(error));

/**
 * get请求
 */
export function get(url: string, params: any) {
    return new Promise((resolve, reject) => {
        http.get(url, {
            params: params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err)
        })
    });
}

/**
 * post请求
 */
export function post(url: string, params: any) {
    return new Promise((resolve, reject) => {
        http.post(url, params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err)
            })
    });
}